<template>
  <div style="height: 70px; line-height: 50px; border-bottom: 1px solid #2c3e50; display: flex">
    <div @click="gotoHome"
         style="width: 250px; cursor: pointer; padding-left: 30px; font-weight: bold; color: black; font-size: 24px; text-align: center; padding-top: 10px">
      宠物健康后台管理
    </div>
    <div style="flex: 1"></div>
    <!-- 下拉菜单 -->
    <div style="width: 100px;">
      <el-dropdown>
        <div style="text-align: center">
          <el-avatar :src="avatar"/>

          <div>{{ username }}</div>
        </div>

        <el-button type="primary">
          <el-icon class="el-icon--right">
            <arrow-down/>
          </el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="$router.push('/adminInfo')">个人信息</el-dropdown-item>
            <el-dropdown-item @click="$router.push('/login')">退出系统</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script>
import {emitter} from "@/utils/eventBus";
import {getUserInfo} from "@/api/user"; // 引入 mitt 实例

export default {
  name: "Header",
  data() {
    return {
      avatar: localStorage.getItem('avatar') ? localStorage.getItem('avatar') : '123', // 初始值
      username: localStorage.getItem('username') ? localStorage.getItem('username') : '123', // 初始值
    };
  },
  methods: {
    getUserInfo() {
      if (this.username !== '123') {
        getUserInfo().then(res => {
          this.avatar = res.data.avatar
        })
      }
    },
    gotoHome() {
      this.$router.push('/');
    },
  },
  mounted() {
    this.getUserInfo(),
        emitter.on('userLoggedIn', (username) => {
          this.username = username;
          localStorage.setItem('username', username)
        });
    emitter.on('userUpdate', (avatar) => {
      this.avatar = avatar;
      localStorage.setItem('avatar', avatar)
      window.location.reload();
    });
  },
  beforeUnmount() {
    // 卸载事件监听器
    emitter.off('userLoggedIn');
    emitter.off('userUpdate');
  },
};
</script>

<style scoped></style>
